<!--注册-->
<template>
  <div class="register">
    
    <div class="regHeader">
    <!-- <div class="regHeader-logo">
      <router-link to="/">
        <img src="../../assets/img/logo.png" alt>
      </router-link>
    </div> -->
    <div class="regHeader-title">
      <h2 v-if="$route.path==='/user/register'">用户注册</h2>
      <h2 v-else-if="$route.path==='/user/modifyPwd'">修改密码</h2>
    </div>
  </div>

    <div class="register-contain">
      <div class="register-contain-left">
        <el-form style="margin: 5% 20%" :model="registerForm" :rules="registerFormRules" ref="registerFormRef" class="demo-ruleForm">
          <!-- <el-form-item label="手 机 号：  " prop="phoneNumber">
            <el-input v-model="ruleForm.phoneNumber" placeholder="手机号"></el-input>
          </el-form-item> -->
          <el-form-item label="用 户 名 ：  " prop="username">
            <el-input v-model="registerForm.username" placeholder="请输入邮箱" clearable></el-input>
          </el-form-item>
          <el-form-item label="验 证 码 ： " prop="code">
            <el-input v-model="registerForm.code" maxlength="8" placeholder="请输入验证码" clearable></el-input>
            <el-button type="success" class="code" @click="sendCode" :disabled="codeBtn.status">{{codeBtn.text}}</el-button>
          </el-form-item>
          <el-form-item label="设置密码：" prop="password">
            <el-input placeholder="请输入密码" maxlength="13" v-model="registerForm.password" clearable></el-input>
          </el-form-item>
          <el-form-item label="确认密码：" prop="checkPass">
            <el-input placeholder="请确认密码" maxlength="13" v-model="registerForm.checkPass" clearable></el-input>
          </el-form-item>
          <el-form-item class="btns">
            <el-button type="primary" :disabled="registerBtnStatus"  @click="register" v-if="$route.path==='/user/register'">注册</el-button>
            <el-button type="primary" :disabled="modifyPwdBtnStatus" @click="modifyPwd" v-else-if="$route.path==='/user/modifyPwd'">确认修改</el-button>
          <el-button type="info" @click="resetRegisterForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="register-contain-right">
        <span>
          已有账号，请
          <router-link to="/login">直接登录</router-link>
        </span>
        <el-button type="primary" class="btns-left">
          <img
            style="width: 20px;
            position: absolute;
            top:10px;
            left:10px;"
            src="../../assets/icon/wb.png"
            alt
          />
          新浪微博登录
        </el-button>
        <el-button type="primary" class="btns-left">
          <img
            style="width: 18px;position: absolute;top:10px;left:10px;"
            src="../../assets/icon/qq.png"
            alt
          />QQ账号登录
        </el-button>
        
        <el-button type="primary" class="btns-left">
          <img
            style="width: 20px;
            position: absolute;
            top:10px;
            left:10px;"
            src="../../assets/icon/wx.png"
            alt
          />微信扫一扫登录
        </el-button>
      </div>
    </div>
    <Footer></Footer>
  </div>
</template>

<script>
import {
    registerAccount,
    modifyPwd,
    getCode
} from '../../api/loginAccount.js'
import {
  stripscript,
  validatePass,
  validateEmail
} from "../../utils/validate";
export default {
  props:['userType'],
  name: "Reg",
  data() {
    // 验证用户名
    let validateUsername = (rule, value, callback) => {
      this.$store.dispatch('validateEmail',{rule, value, callback})
    };
    // 验证密码
    let validatePassword = (rule, value, callback) => {
      this.$store.dispatch('validatePassword',{rule, value, callback})
    };
    // 验证重复密码
    let validatePasswords = (rule, value, callback) => {
      // this.$store.dispatch('validatePasswords',{rule, value, callback})
      if (stripscript(value) === "") {
        callback(new Error("请再次输入密码"));
      } else if (stripscript(value) != this.registerForm.password) {
        callback(new Error("重复密码不正确"));
      } else {
        callback();
      }
    };
    // 验证验证码
    let validateCode = (rule, value, callback) => {
      this.$store.dispatch('validateCode',{rule, value, callback})
    };
    return {
      text: "123",
      input: "",
      // 发送验证码按钮
      codeBtn:{
        status: false,
        text: "点击发送"
      },
      // 注册按钮
      registerBtnStatus:true,
      modifyPwdBtnStatus:true,
      count:"",
      timer:null,
      // 返回的code
      returnCode:'',
      registerForm: {
        id:'3',
        username: "",
        password: "",
        checkPass: "",
        code:""
      },
      registerFormRules: {
        username: [{  required: true,validator: validateUsername, trigger: "blur" }],
        password: [{  required: true,validator: validatePassword, trigger: "blur" }],
        checkPass: [{  required: true,validator: validatePasswords, trigger: "blur" }],
        code: [{  required: true,validator: validateCode, trigger: "blur" }]
      }
    };
  },
  methods: {
    /* submitForm(formName) {
      console.log(this.ruleForm.phoneNumber + " " + this.ruleForm.password);
      var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[4-9]{1})|(18[0-9]{1})|(199))+\d{8})$/;
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.ruleForm.phoneNumber);
          if (!myreg.test(this.ruleForm.phoneNumber)) {
            alert("请输入有效的手机号码！");
            this.ruleForm.phoneNumber = "";
          } else {
            axios({
              url: URL.createUser,
              method: "post",
              params: {
                phone_number: this.ruleForm.phoneNumber,
                password: this.ruleForm.password
              }
            })
              .then(res => {
                if (res.data.success == true) {
                  alert("注册成功！");
                  this.ruleForm.phoneNumber = this.ruleForm.password = this.ruleForm.checkPass =
                    "";
                  this.$router.push("/login");
                } else if (res.data.success == false) {
                  alert(res.data.msg);
                }
              })
              .catch(err => {
                console.log(this.phoneNumber + " " + this.password);
                alert("注册失败！");
                console.log(err);
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }, */
    // 重置表单
    resetRegisterForm () {
      this.$refs.registerFormRef.resetFields()
    },
    register () {
      this.$refs.registerFormRef.validate(valid => {
        if (!valid) return
        // 在调用修改密码接口之前先确认验证码是否正确
        // this.checkCode();

        // 在调用修改密码接口之前先确认验证码是否正确
        console.log(this.registerForm.code);
        console.log(this.returnCode);
        if(this.registerForm.code!==this.returnCode){
          this.$message({
            message: '验证码错误，请重新获取',
            type: 'error'
          })
          // 还原验证码按钮默认状态
          this.codeBtn={
            status: false,
            text: "重新获取"
          };
          // 清除倒计时
          clearInterval(this.timer);
          // clear Form
          this.$refs.registerFormRef.resetFields()
          return
        }
        this.registerForm.id = (parseInt(Math.random() * 100)).toString() // mock a id
        const para = Object.assign({}, this.registerForm)
        console.log(para)
        registerAccount(para).then(res => {
          console.log(res);
          if(res.data.code===1){
            // this.$message.error(res.data.message);
            this.$message({
              message: res.data.data.message,
              type: 'error'
            })
          }else{
            // this.$message.success(res.data.message);
            this.$message({
              message: res.data.data.message,
              type: 'success'
            })
            /* this.$refs['editForm'].resetFields()
            this.dialogFormVisible = false
            this.getUsers()  */
            this.$refs.registerFormRef.resetFields()
            this.$router.push("/login");
          }
        })
      })
    },
    modifyPwd(){
      this.$refs.registerFormRef.validate(valid => {
        if (valid) {
          this.$confirm('确认修改密码吗？', '提示', {})
            .then(() => {
              // 在调用修改密码接口之前先确认验证码是否正确
              console.log(this.registerForm.code);
              if(this.registerForm.code!==this.returnCode){
                this.$message({
                  message: '验证码错误，请重新获取',
                  type: 'error'
                })
                // 还原验证码按钮默认状态
                this.codeBtn={
                  status: false,
                  text: "重新获取"
                };
                // 清除倒计时
                clearInterval(this.timer);
                // clear Form
                this.$refs.registerFormRef.resetFields()
                return
              }
              const para = Object.assign({}, this.registerForm)
              // this.$http.get('/user/edit',para).then(res => {
              modifyPwd(para).then(res => {
                console.log(res);
                if(res.data.code===1){
                  // this.$message.error(res.data.message);
                  this.$message({
                    message: res.data.data.message,
                    type: 'error'
                  })
                }else{
                  // this.$message.success(res.data.message);
                  this.$message({
                    message: res.data.data.message,
                    type: 'success'
                  })/* this.$refs['editForm'].resetFields()
                  this.dialogFormVisible = false
                  this.getUsers()  */
                  this.$refs.registerFormRef.resetFields()
                  this.$router.push("/login");
                }
              })
            })
            .catch(e => {
              // 打印一下错误
              console.log(e)
            })
        }
      })
    },
    sendCode(){
      // 进行提示
      if (this.registerForm.username == "") {
        this.$message.error("邮箱不能为空！！");
        return false;
      }
      if (validateEmail(this.registerForm.username)) {
        this.$message.error("邮箱格式有误，请重新输入！！");
        return false;
      }
      // 调用发送验证码接口
      const para = this.registerForm.username;
      console.log(para);
      var _that=this;
      // 修改获取验证按钮状态，变成不可用
      this.codeBtn = {
        status: true,
        text: "发送中"
      };
      getCode(para).then(res => {
        console.log(res);
        /* if(res.data.code===1){
          // this.$message.error(res.data.message);
          this.$message({
            message: res.data.data.message,
            type: 'error'
          })
          this.codeBtn = {
            status: false,
            text: "重新发送"
          };
        }else{ */

          // this.$message.success(res.data.message);
          this.$message({
            message: res.data.data.message,
            type: 'success'
          })
          /* this.$refs['editForm'].resetFields()
          this.dialogFormVisible = false
          this.getUsers()  */
          
          this.registerBtnStatus=false;
          this.modifyPwdBtnStatus=false;
          // 倒计时
          this.countDown(60);
          // _that.codeBtn.text=60
          // save code
          this.returnCode=res.data.data.vcode;
      })
    },
    countDown(count){
      // 60 和 0不见了，故意留BUG
      // setTimeout:clearTimeout(变量)  只执行一次
      // setInterval:clearInterval(变量))  不断的执行，需要条件才会停止
      // 判断定时器是否存在，存在则清除
      if (!this.timer) {
        this.count = count;
        var _that = this
        this.timer = setInterval(() => {
          // 注意此时的this不再指向了vue，而是指向了window
          _that.count--;
          if (_that.count === 0) {
            // 0秒后清除定时器
            clearInterval(this.timer);
            _that.codeBtn({
              status: false,
              text: "再次获取"
            });
          } else {
            _that.codeBtn.text = `${_that.count}秒`; // es5 '倒计时' + time + '秒'
          }
        }, 1000);
        // clearInterval(timer.value);
      }
    },
    clearCountDown(){
      // 还原验证码按钮默认状态
      this.codeBtn({
        status: false,
        text: "重新获取"
      });
      // 清除倒计时
      clearInterval(this.timer);
    },
    checkCode(){
      console.log(this.registerForm.code);
      if(this.registerForm.code!=="070816"){
        this.$message({
          message: '验证码错误',
          type: 'error'
        })
        this.clearCountDown();
        return
      }
    }
  }
};
</script>

<style scoped>

  .regHeader {
    width: 1000px;
    height: 72px;
    margin: 0 auto;
    position: relative;
  }
  .regHeader-logo img {
    margin-top: 30px;
  }
  .regHeader-title {
    width: 110px;
    height: 35px;
    position: absolute;
    left: 130px;
    top: 25px;
    text-align: center;
    letter-spacing: 3px;
    /* border-left: 1px solid #ccc; */
    line-height: 35px;
  }

  .register {
    margin: 10px auto;
    width: 1000px;
  }
  .register-contain {
    width: 100%;
    height: 550px;
    border-top: 2px solid #2f5895;
    border-bottom: 2px solid #2f5895;
  }
  .register-contain-left {
    margin: 20px 0;
    float: left;
    width: 645px;
    height: 460px;
    border-right: 1px solid #dcdcdc;
    font-family: "Microsoft YaHei";
  }
  .register-contain-right {
    float: left;
    width: 270px;
    padding: 80px 40px;
    font-size: 14px;
  }
  .register-contain-right span {
    padding-left: 10px;
    line-height: 54px;
    font-size: 16px;
    color: #333;
  }
    .register-contain-right span  a {
      color: blue;
    }
  
  p {
    line-height: 50px;
    font-size: 14px;
    color: #909090;
  }
  .btns-left {
    width: 150px;
    margin: 10px;
    padding: 12px 30px;
    position: relative;
  }
    .btns {
      display: flex;
      justify-content: space-between;
    }
    .el-form-item {
      width:800px;
    }
  .el-input {
    width:300px;
    margin-right:20px;
  }
</style>
